# 寻找相似用户
import json
import numpy as np
from pearson_score import pearson_score


def find_similar_users(dataset,user,num_users):
    if user not in dataset: # 判断用户是否在数据集中
        raise TypeError('User'+user+'不在数据集中')
    # 为所有用户计算皮尔逊相关系数
    scores = np.array([[x,pearson_score(dataset,user,x)] for x in dataset if x!=user])
    # 评分基于第二列排序
    scores_sorted = np.argsort(scores[:,1])
    # 评分按照降序排列(高分在前）
    scored_sorted_dec = scores_sorted[::-1]
    # 提取k个最高分
    top_k = scored_sorted_dec[0:num_users]
    return scores[top_k]


if __name__ == '__main__':
    data_file = 'F:\python学习资料\Python-Machine-Learning-Cookbook-master\Chapter05\movie_ratings.json'
    with open(data_file,'r') as f:
        data = json.loads(f.read())

    user = 'John Carson'
    print("Users similar to "+user+':\n')
    similar_users = find_similar_users(data,user,3)
    print("Users\t\tSimilarity score\n")
    for item in similar_users:
        print(item[0],'\t\t',round(float(item[1]),2))